package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_LIST_KEY;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_LIST_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result getList() throws JsonProcessingException {
        //1.从redis中查询列表
        List<String> list = stringRedisTemplate.opsForList().range(CACHE_SHOP_LIST_KEY, 0, -1);

        //2.判断是否存在
        if (list != null && list.size() > 0) {
            List<ShopType> typeList = new ArrayList<>();
            for (String str : list) {
                typeList.add(JSONUtil.toBean(str,ShopType.class));
            }
            //3.存在直接返回
            return Result.ok(typeList);
        }
        //4.不存在，查数据库
        List<String> stringList = new ArrayList<>();
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //5.不存在报错
        if (typeList == null){
            return Result.fail("列表不存在");
        }
        for (ShopType shopType : typeList) {
            stringList.add(JSONUtil.toJsonStr(shopType));
        }
        //6.存在保存到redis中
        stringRedisTemplate.opsForList().rightPushAll(CACHE_SHOP_LIST_KEY, stringList);
        stringRedisTemplate.expire(CACHE_SHOP_LIST_KEY,CACHE_SHOP_LIST_TTL, TimeUnit.MINUTES);
        //7.返回
        return Result.ok(typeList);
    }
}
